#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <strings.h>
#include <ctype.h>
#include <string.h>

int main(int argc, char *argv[]){

    // 参数
    if (argc < 3){
        fprintf(stderr, "Usgae argv ... \n");
        exit(-1);
    }

    // 文件描述符
    int cfd = socket(PF_INET, SOCK_STREAM, 0);
    if(cfd < 0){
        fprintf(stderr, "socket error \n");
        exit(-1);
    } 

    // 连接
    struct sockaddr_in ser_addr;
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_addr.s_addr = inet_addr(argv[1]);
    ser_addr.sin_port = htons(atoi(argv[2]));
    if (connect(cfd, (struct sockaddr *)&ser_addr, sizeof(ser_addr)) < 0){
        fprintf(stderr, "connect error \n");
        exit(-1);
    }

    // 通信
    char buf[1024];
    int n;    
    while (1){
        fputs("Message(q is quit): ", stdout);
        fgets(buf, sizeof(buf), stdin);
        if(!strcmp(buf, "q\n") || !strcmp(buf, "Q\n")){
            printf("Quit connected!\n");
            break;
        }
        write(cfd, buf, strlen(buf));
        memset(buf, '\0', sizeof(buf));
        n = read(cfd, buf,sizeof(buf));  
        printf("Get message from server: [%d] %s\n", n, buf);
    }
    
    
    close(cfd);
    return 0;
}